package com.ash.android_adk_demo
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import com.ash.android_adk_demo.databinding.ActivityMainBinding
import com.ash.base.bean.HcResult
import com.ash.base.bean.Schemes
import com.ash.base.bean.SecureSolution
import com.ash.base.bean.Solution
import com.ash.base.logd
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.hc.hcsdk.HCSDK
import com.hc.player.common.IPlayerListener
import com.hc.player.common.PlayerEventBus
import com.hc.player.player.ASMRPlayer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@RequiresApi(Build.VERSION_CODES.O)
class MainActivity : ComponentActivity(), OnClickListener {

    val TAG = "MainActivity"

    lateinit var hcSdk: HCSDK

    //    配置信息
    val channelCode = "yshrkz";
    val userId = "c9eea403-3f5f-11ef-9c91-00163e3195fd";

    // 初始化播放器
    val player: ASMRPlayer by lazy { ASMRPlayer(applicationContext) }

    val playerListener =
        object : IPlayerListener {
            /*音频准备完毕*/
            override fun onCacheAllDone(exception: java.lang.Exception?) {
                Log.e(TAG, "onAllDone")
                player.play()
            }

            /*音频预加载完毕*/
            override fun onCachePreDownloadDone() {
                Log.e(TAG, "onPreDownloadDone")
                player.play()
            }

            /*加载失败*/
            override fun onCacheError(e: java.lang.Exception) {
                Log.e(TAG, "onError")
            }

            override fun onClearCache() {
                Log.e(TAG, "onClearCache")
            }

            override fun onTick(tick: Long) {
                Log.e(TAG, "onTick")
            }

            override fun onFinished() {
                Log.e(TAG, "onFinished")
            }

            override fun onPlay() {
                Log.e(TAG, "onPlay")
            }

            override fun onPause() {
                Log.e(TAG, "onPause")
            }

            override fun onPlayError(e: java.lang.Exception) {
                Log.e(TAG, "onPlayError")
            }
        }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    override fun onTrimMemory(level: Int) {
        Log.e(TAG, "onTrimMemory: ")
        super.onTrimMemory(level)
    }

    val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }



    fun bindClick() {
        binding.rvParentList.layoutManager = LinearLayoutManager(this)

        binding.btnLogin.setOnClickListener(this)
        binding.btnStop.setOnClickListener(this)
        //        疗愈方案列表
        binding.btnQueryCures.setOnClickListener(this)
        binding.btnZbjs.setOnClickListener(this)
        binding.btnSchedule.setOnClickListener(this)
    }

    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate: ")
        try {
            hcSdk = HCSDK.getShared(this)
            hcSdk.initialize(
                channelCode, // 渠道码
                com.ash.base.AppConfig.getPathPrefix(), // 产品工程，默认填此即可
                host = "http://47.100.120.192",  // host，正式使用时可不填
            )
            setContentView(binding.root)
            if(hcSdk.isLogin()){
                binding.tvStatus.text = "已登录    "
            }
            bindClick()
            PlayerEventBus.instance.addLisenter(playerListener)
        } catch (e: Exception) {
            "${e.message}".logd()
        }
    }

    fun playCure(scheme: Schemes, duration: Int = 20) {

        Log.d(TAG, "solution:======播放====== ${scheme.id} ${duration}")
        CoroutineScope(Dispatchers.Main).launch {
            try {
                val result =
                    withContext(Dispatchers.IO) {
                        hcSdk.provider.getSolution(
                            scheme.id.toString(),
                            duration,
                            cureName = scheme?.schemeName ?: "empty"
                        )
                    }
                // 判断是离线还是在线方案：离线和保底返回的是Solution 在线返回的是加密的SecureSolution
                if (result is HcResult.Success) {
                    if (result.data is SecureSolution) {
                        // 在线方案
                        val solution: SecureSolution = result.data as SecureSolution

                        // 播放预备
                        "在线播放prepare".logd()
                        player.prepare(solution.audioPlans, duration.toLong(), isCipher = true)
                    } else if (result.data is Solution) {
//                        离线方案
                        "离线播放prepare".logd()
                        val solution: Solution = result.data as Solution
                        player.prepare(solution)
                    }
                } else if (result is HcResult.Error) {
                    result.mess.logd()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) { toast(e.toString()) }
            }
        }
    }

    fun toast(msg: String) {
        runOnUiThread{
            Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_login -> {
                // 基于 coroutines 的并发
                CoroutineScope(Dispatchers.Main).launch() {
                    try {
                        withContext(Dispatchers.IO) {
                            hcSdk.login(
                                // 当前用户的唯一标识
                                userId,
                            )
//                            登录失败会抛出异常，此处捕获异常并提示登录失败
                        }
                        withContext(Dispatchers.Main) {
                            binding.tvStatus.text = "已登录    "
                            toast("succeed in login")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, e.toString())
                        withContext(Dispatchers.Main) { toast(e.toString()) }
                    } finally {}
                }
            }
            R.id.btn_stop -> {
                player.stop()
            }
            R.id.btn_query_cures -> {
                CoroutineScope(Dispatchers.Main).launch {
                    try {
                        val result = withContext(Dispatchers.IO) { hcSdk.provider.getSchemeList() }
                        if (result is HcResult.Success) {
                            "请求列表：${result.data}".logd()
                            var cures = result.data
                            val adapter = ParentAdapter(cures)

                            adapter.setOnItemClickLitener(
                                object : ParentAdapter.OnItemClickLitener {
                                    override fun onItemClick(view: View, scheme: Schemes) {
                                        val jsonStr = scheme.extConfigJson
                                        var jsonObject = Gson().fromJson(jsonStr, JsonObject::class.java)
                                        val jsList = jsonObject.get("durations").asJsonArray
                                        var l = mutableListOf<String>()
                                        for (value in jsList) {
                                            l.add(value.asString)
                                        }
//                                        示例播放第一个时长
                                        playCure(scheme, l[0].toInt())
                                    }
                                }
                            )
                            binding.rvParentList.adapter = adapter
                        } else if (result is HcResult.Error) {
                            result.mess.logd()
                        }
                        withContext(Dispatchers.Main) { toast("queryCures ok") }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        withContext(Dispatchers.Main) { toast(e.toString()) }
                    }
                }
            }
            R.id.btn_zbjs ->{
                startActivity(
                    Intent(this,PsyActivity::class.java))
            }
            R.id.btn_schedule ->{
                startActivity(
                    Intent(this,ScheduleActivity::class.java))
            }
        }
    }
}
